package com.life.wd.controller;

import com.life.wd.dto.GoodsAddRequest;
import com.life.wd.dto.GoodsQueryRequest;
import com.life.wd.dto.GoodsUpdateRequest;
import com.life.wd.entity.Goods;
import com.life.wd.result.PageResult;
import com.life.wd.result.Result;
import com.life.wd.service.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/goods")
@Slf4j
@Api(tags = "商品管理")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    /**
     * 添加商品
     */
    @PostMapping("/add")
    @ApiOperation("添加商品")
    public Result<Long> addGoods(@Valid @ModelAttribute GoodsAddRequest request) {
        log.info("添加商品请求参数: {}", request);
        try {
            Long goodsId = goodsService.addGoods(request);
            return Result.success(goodsId);
        } catch (Exception e) {
            return Result.error("添加商品失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询商品列表
     */
    @GetMapping("/list")
    @ApiOperation("分页查询商品列表")
    public Result listGoods(GoodsQueryRequest request) {
        PageResult result = goodsService.listGoods(request);
        return Result.success(result);
    }

    /**
     * 更新商品
     */
    @PostMapping("/update")
    @ApiOperation("更新商品")
    public Result<Boolean> updateGoods(@Valid @ModelAttribute GoodsUpdateRequest request) {
        log.info("更新商品请求参数: {}", request);
        try {
            boolean success = goodsService.updateGoods(request);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("更新商品失败: " + e.getMessage());
        }
    }

    /**
     * 删除单个商品
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除单个商品")
    public Result<Boolean> deleteGoods(@PathVariable Long id) {
        try {
            boolean success = goodsService.deleteGoods(id);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("删除商品失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除商品
     */
    @DeleteMapping("/batch")
    @ApiOperation("批量删除商品")
    public Result<Boolean> deleteGoodsBatch(@RequestBody List<Long> ids) {
        try {
            boolean success = goodsService.deleteGoodsBatch(ids);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("批量删除商品失败: " + e.getMessage());
        }
    }
}
